<template>
	<view class="_abbr">
		<view class="public">
			<view>
				<view class="scan-item">
					<u-form :model="orderForm" ref="uForm">
						<u-form-item label-width="180rpx" prop="name">
							<view class="put" @click="getData()">
								<u-input placeholder="选择工单号"  @click="getData()" class="put-w"
									v-model="orderForm.name" />
							</view>
						</u-form-item>
					</u-form>
					<!--选择器搜索组件-->
					<pickerSearch style="z-index: 9999;" v-model="isOrderOpen" :dataSource='orderOptions' :pickerValues="[0]" @recload='confirmOrder'></pickerSearch>
				</view>
				<view class="scan-item scan-item1">
					<u-input v-model="subForm.sn" placeholder="扫描或输入sn" border="false" :show-action="false"></u-input>
					<view class="right-icon">
						<view class="icon" @click="doScan1">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item scan-item1">
					<u-input v-model="subForm.an" placeholder="扫描或输入an" border="false" :show-action="false"></u-input>
					<view class="right-icon">
						<view class="icon" @click="doScan2">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view>
					<view>现场照片</view>
					<view>
						<u-upload 
							:fileList="fileList1" 
							@afterRead="afterRead" 
							@delete="deletePic" 
							name="1" 
							:maxCount="1">
						</u-upload>
					</view>
				</view>
			</view>
		</view>
		<view class="public">
			<view class="button">
				<u-button type="primary" @click="sub" text="确定"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	import loginVue from '../../../user/login.vue';
	import pickerSearch from '@/compoments/pickerSearch.vue'
	export default {
		name: 'detail',
		components: {pickerSearch},
		data() {
			return {
				isOrderOpen:false, //选择工单号组件弹出
				orderForm: {}, //选择的当前工单号
				workOrderId: '', // 工单号
				orderOptions: [], //工单号选项
				deviceForm: {}, //设备详情数据
				subForm: {
					workOrderId: undefined,
					sn: undefined, // sn
					an: undefined, // an
					mediaId: undefined
				},
				fileList1: [], //设备照片
				deviceImages: {
					workOrderId: '',
					mediaType: "1100",
					mediaName: '设备照片',
					fileUrls: []
				},
			}
		},
		onLoad(options) {
			uni.showLoading({
				title:'正在加载中'
			})
			this.BaseUrl = getApp().globalData.baseURL;
			uni.hideLoading()
		},
		methods: {
			reset() {
				this.fileList1 = []
				this.orderForm = {}
				this.subForm = {}
			},
			// 扫码
			doScan1() {
				uni.scanCode({
					success: (res) => {
						this.subForm.sn = res.result
					}
				})
			},
			doScan2() {
				uni.scanCode({
					success: (res) => {
						this.subForm.an = res.result
					}
				})
			},
			// 获取待入库数据
			getData() {
				request({
					url: "system/order/list",
					data: {
						workOrderStatusIds: '11,13,14,15,16',
						customerCompanyId: "237"
					}
				}).then(res => {
					this.orderOptions = res.rows.map((item, index) => {
						return {id: index + 1, name: item.workOrderId}
					})
					this.isOrderOpen = true
				})
			},
			confirmOrder(data) {
				this.orderForm = data
				this.subForm.workOrderId = data.name
			},
			// 提交
			sub() {
			  // console.log(this.subForm);
			  this.deviceImages.workOrderId = this.subForm.workOrderId;
			  if (!this.subForm.workOrderId) {
			    uni.showToast({
			      title: '请选择工单号',
			      icon: 'none'
			    });
			    return;
			  }
			  if (!this.subForm.sn && !this.subForm.an) {
			    uni.showToast({
			      title: '请填写sn或者an',
			      icon: 'none'
			    });
			    return;
			  }
			  if (this.fileList1.length === 0) {
			    uni.showToast({
			      title: '请上传照片',
			      icon: 'none'
			    });
			    return;
			  }
			  // 照片
			  request({
			    url: 'system/orderMedia',
			    method: 'POST',
			    data: this.deviceImages
			  }).then(res => {
			    console.log("1", res, res.data);
			    this.subForm.mediaId = res.data;
			
			    // mediaId赋值之后再调用提交form的请求
			   if(res.code === 200) {
				   return request({
				     url: 'system/alibabaRecycleScan',
				     method: "POST",
				     data: this.subForm
				   }).then(res => {
				     this.reset();
				   });
			   }
			  });
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						// console.log(res);
						if (res.data.code === 500) {
							uni.showToast({
								title:'该图片已经上传过，请重新上传',
								icon:'none'
							})
							this.fileList1 = []
							return
						}
						if (name == 1) {
							this.deviceImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						}
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {
			
					})
				})
			},
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "110": 
							if (dataElement.fileUrl !== null) {
								this.fileList1.push({
									type: "image",
									url: dataElement.fileUrl,
									status: "success",
									name: "",
									message: "",
									thumb: "",
									size: 60489
								})
							}
						default:
							continue;
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		background-color: rgba(244, 249, 254, 1);
		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);
			.title {
				font-size: 20px;
				padding: 8px 0;
				margin-bottom: 12px;
				border-bottom: 1px solid rgba(0, 124, 233, 0.4);
			}
			.scan-item {
				margin: 10px 0;
				.right-icon {
					position: relative;
					box-sizing: border-box;
					position: sticky;
					top: 0;
					z-index: 999;
					display: flex;
					overflow: hidden;
					justify-content: space-around;
					background: rgb(255, 255, 255);
					margin: 6px;
					.scan {
						position: absolute;
						top: 8upx;
						right: 14px;
					}
				}
			}
			.scan-item1 {
				display: flex; border: 1px solid #eee;
			}
		}
	}
</style>